<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <div >
    <!-- <Divider />
    <div style="display: flex;justify-content: space-between;align-items: center;padding: 0 10px 10px;">
      <h3>
        说明：要保证模板存货编码不重复
      </h3>
      <a-button type="primary" @click="handlestep2TableAdd()" >
        <Icon icon="fluent:add-12-filled" /> {{ t('添加模板') }}
      </a-button>
    </div> -->
    <Divider />
    <div style="display: flex;">

      <BasicTable @register="registerTable" style="flex: 1;">
        
        <template #firstColumn="{ record }">
          <a @click="handleForm(record)">
            {{ record.code }}
          </a>
        </template>
      </BasicTable>
      <BasicForm @register="registerForm" style="flex: 1;margin-left: 10px;">
        <template #childList>
          <BasicTable @register="registerChildTable" >
          </BasicTable>
        </template>
      </BasicForm>
        

    </div>


    <div style="width: 100%;display: flex;justify-content: center;margin-top: 20px;">
      <a-button type="default" @click="customResetFunc()" style="margin-right: 100px;">上一步</a-button>
      <a-button type="primary" @click="customSubmitFunc()">确认价格调整</a-button>
    </div>
    <InputForm @register="registerDrawer" @success="handleSuccess" />

    
    <BasicModal @register="registerModal" :title="'是确认调整价格?'" @ok="handleSubmit" @cancel="cancel" width="30%">
      <div class="text-2xl text-center text-inherit">
        是否确认提交？<span class="text-red-500 text-3xl" v-if="seconds !=0 ">{{seconds}}</span>
      </div>
      <div style="color: red;margin-top: 40px;text-align: center;">
        当客户较多时，检查时间可能较长，请耐心等待!(可关闭后稍后去查看生成结果)
      </div>
    </BasicModal>
    <!-- <WecharPriceModelInv @register="registerDrawer2" @success="handleSuccess" />
    <FormImport @register="registerImportModal" @success="handleSuccess" /> -->
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsSettingPricemodelWecharPriceModelUseStepStep4',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref,defineProps ,onMounted  } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { wecharPriceModelDelete, wecharPriceModelListData } from '/@/api/setting/pricemodel/wecharPriceModel';
  import { wecharPriceModelDisable, wecharPriceModelEnable } from '/@/api/setting/pricemodel/wecharPriceModel';
  import { wecharPriceSystemTreeData } from '/@/api/setting/pricemodel/wecharPriceSystem';
  import { wecharPriceModelInvCheck  } from '/@/api/setting/pricemodel/wecharPriceModelInv';
  import { wecharPriceModelUseSave  } from '/@/api/setting/pricemodel/wecharPriceModelUse';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputForm from './Step2Form.vue';
  import { Divider } from 'ant-design-vue';
  import { ListSelect } from '/@/components/ListSelect';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  const emit = defineEmits(['next', 'prev']);

  import { useModal,BasicModal } from '/@/components/Modal';
  const [registerModal, { openModal,closeModal,setModalProps }] = useModal();
  const { t } = useI18n('setting.pricemodel.wecharPriceModel');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('价格模板管理'),
  };
  const listSelectRef = ref<any>(null);
  const selectListRef = ref<any>([]);

    const props = defineProps({
      data: Object,
      modelList:Array
    });
  async function customResetFunc() {
    emit('prev');
  }
  let seconds = ref(5)
  let countdownInterval = ref(null)

  function countdown() {
    countdownInterval.value = setInterval(function() {
      if (seconds.value == 1) {
        clearInterval(countdownInterval.value);
        setModalProps({ confirmLoading: false });
        
      }
      seconds.value--;
    }, 1000);
  }

  function cancel(){
    clearInterval(countdownInterval.value);
  }

  async function handleSubmit() {
    

    try {
      setModalProps({ confirmLoading: true });
      let arr = await childTable.getDataSource()
      arr = arr.map(item=>{
        return item.code
      })
      let cusCodes = arr.join(',')
      let params = getFieldsValue()
      let data = {
        ...params,
        cusCodes,
        modelList:props.modelList
      }
      
      const res = await wecharPriceModelUseSave(params, data);
      showMessage(res.message);
      setTimeout(closeModal);
      emit('next', {});
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('提交失败！'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
    // let params = {
    //   ...props.data,
    //   modelList:props.modelList
    // }
    // setTimeout(closeModal);
    // emit('next', {});
  }

  async function customSubmitFunc() {
    seconds.value = 5
    setModalProps({ confirmLoading: true });
    openModal(true,{})
    countdown()
    // emit('next', {});
    // try {
    //   const values = await validate();
    //   setProps({
    //     submitButtonOptions: {
    //       loading: true,
    //     },
    //   });
    //   setTimeout(() => {
    //     setProps({
    //       submitButtonOptions: {
    //         loading: false,
    //       },
    //     });
    //     emit('next', values);
    //   }, 1500);
    // } catch (error) {
    //   console.error(error);
    // }
  }

  const inputFormSchemas: FormSchema[] = [
    // {
    //   label: '',
    //   field: 'cusCode',
    //   fieldLabel: 'cusName',
    //   component: 'ListSelect',
    //   componentProps: {
    //     selectType: 'empUserSelect',
    //   },
    //   dynamicDisabled: true,
    // },
    // {
    //   label: '',
    //   field: 'cusCode',
    //   component: 'Input',
    //   componentProps: {
    //   },
    //   dynamicDisabled: true,
    // },
    {
      label: '',
      field: 'paramClearHisPrice',
      component: 'CheckboxGroup',
      componentProps: {
        // dictType: 'sys_yes_no',
        options: [{ label: '是否清除现有价格', value: '1' }],
      },
      colProps: { lg: 8, md: 24 },
    },
    {
      label: '',
      field: 'paramReplaceHisPrice',
      component: 'CheckboxGroup',
      componentProps: {
        // dictType: 'sys_yes_no',
        options: [{ label: '是否覆盖已有价格', value: '1' }],
      },
      colProps: { lg: 8, md: 24 },
    },

    {
      label: '模板编码',
      field: 'modelCode',
      component: 'Input',
      componentProps: {
      },
      dynamicDisabled: true,
      show:false
    },
    {
      label: '模板名称',
      field: 'modelName',
      component: 'Input',
      componentProps: {
      },
      dynamicDisabled: true,
      show:false
    },
     {
      label: '',
      field: 'childList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'childList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate }] = useForm({
    labelWidth: 140,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const tableColumns: BasicColumn[] = [
    {
      title: t('模板编号'),
      dataIndex: 'code',
      key: 'a.code',
      sorter: true,
      width: 100,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('模板名称'),
      dataIndex: 'name',
      key: 'a.name',
      sorter: true,
      width: 200,
      align: 'left',
    },
    {
      title: t('价格体系'),
      dataIndex: 'priceSys.name',
      key: 'a.sys_code',
      sorter: true,
      width: 150,
      align: 'left',
    },
    {
      title: t('模板说明'),
      dataIndex: 'remarks',
      key: 'a.remarks',
      sorter: true,
      width: 200,
      align: 'left',
    },
    // {
    //   title: t('创建时间'),
    //   dataIndex: 'createDate',
    //   key: 'a.create_date',
    //   sorter: true,
    //   width: 130,
    //   align: 'center',
    // },
    // {
    //   title: t('创建人'),
    //   dataIndex: 'createByName',
    //   key: 'a.create_by_name',
    //   sorter: true,
    //   width: 80,
    //   align: 'left',
    // },
    // {
    //   title: t('状态'),
    //   dataIndex: 'status',
    //   key: 'a.status',
    //   sorter: true,
    //   width: 80,
    //   align: 'center',
    //   dictType: 'sys_search_status',
    // },
    
    
  ];

  const actionColumn: BasicColumn = {
    width: 60,
    actions: (record: Recordable) => [
      {
        icon: 'ant-design:table-outlined',
        // color: 'success',
        title: t('查看价格模板明细'),
        onClick: handleTable.bind(this, record),
        auth: 'setting:pricemodel:wecharPriceModel:edit',
      },
      // {
      //   icon: 'ant-design:delete-outlined',
      //   color: 'error',
      //   title: t('删除价格模板'),
      //   popConfirm: {
      //     title: t('是否确认删除价格模板'),
      //     confirm: handleDelete.bind(this, { code: record.code }),
      //   },
      //   auth: 'setting:pricemodel:wecharPriceModel:edit',
      // },
    ],
  };

  function handlestep2TableAdd() {
    selectListRef.value = [];
    listSelectRef.value.openSelectModal();
  }

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawer2, { openDrawer:openDrawer2 }] = useDrawer();
  const [registerTable, step4Table] = useTable({
    // api: wecharPriceModelListData,
    // beforeFetch: (params) => {
    //   return params;
    // },
    columns: tableColumns,
    actionColumn: actionColumn,
    ellipsis:false,
    // formConfig: searchForm,
    showTableSetting: false,
    useSearchForm: false,
    canResize: true,
    resizeHeightOffset:90,
    pagination: false,
    rowKey: 'code',
    // rowSelection: {
    //   type: 'checkbox',
    // },
  });

  onMounted(async () => {
    let modelCode = ''
    let modelName = ''

    await props.modelList.forEach(item=>{
      modelCode +=  `${item.code},`
      modelName +=  `${item.name},`
    })
    modelCode = modelCode.slice(0, -1);
    modelName = modelName.slice(0, -1);

    setFieldsValue({
      ...props.data,
      modelCode,
      modelName
    })
    step4Table.setTableData(props.modelList|| []);
    childTable.setTableData(props.data.list|| []);
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  // 表格弹窗
  function handleTable(record: Recordable) {
    openDrawer(true, record);
  }


  async function handleEnable(record: Recordable) {
    const res = await wecharPriceModelEnable(record);
    showMessage(res.message);
    handleSuccess();
  }

  

  function handleSuccess() {
    reload();
  }

  const tableColumns2: BasicColumn[] = [
    {
      title: '客户编码',
      dataIndex: 'code',
      width: 100,
      align: 'left',
    },
    {
      title: '客户名称',
      dataIndex: 'name',
      width: 160,
      align: 'left',
    },
    {
      title: '所属分公司',
      dataIndex: 'exDefine12',
      width: 160,
      align: 'left',
    },
    
  ];


  const [registerChildTable, childTable] = useTable({
    // indexColumnProps:{
    //   width: 40,
    // },
    columns: tableColumns2,
    rowKey: 'code',
    pagination: false,
    bordered: true,
    // inset: true,
    canResize:true,
    resizeHeightOffset:90,
  });




</script>